//
//  ViewController.m
//  CatchCrash
//
//  Created by 萨斯辈的呼唤 on 14-7-23.
//  Copyright (c) 2014年 萨斯辈的呼唤. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, retain)UIWebView *webView;

@end

@implementation ViewController

const char *UncaughtExceptionHandler(NSException *exception)
{
    
    NSString *APPVersionName = [[[NSBundle mainBundle] infoDictionary] objectForKey:
                                @"CFBundleDisplayName"];
    NSString *APPBulidName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
    NSString *name = @"1213125967@qq.com";
    
    
    // 异常类型
    NSString *ex_name = [exception name];
    
    //获取异常信息
    NSArray *arr = [exception callStackSymbols];
    NSString *reason = [exception reason];
    
    //构造Mail URL，也可以做成弹出框等其他方式保存或者展示提示信息 根据需求自己做一定的修改
    NSString *urlStr = [NSString stringWithFormat:@"Thanks for your coorperation!<br><br>"
                        "AppName:%@<br>"\
                        "Version:%@<br>"\
                        "Build:%@<br>"\
                        "Detail:<br>%@<br>%@<br>%@<br><br>",
                        APPVersionName, APPBulidName, name,
                        ex_name, arr, reason];
    //调用系统能力 发送邮件
    NSURL *url = [NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    [[UIApplication sharedApplication] openURL:url];
    return [urlStr cStringUsingEncoding:NSUTF8StringEncoding];
}

- (NSInteger)problemWithA:(NSInteger) a B:(NSInteger) b
{
    return a / b;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(20, 100, 280, 300)];
    _webView.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_webView];
    [_webView release];
    
    NSInteger a = 5;
    NSInteger b = 0;
    NSInteger c = 0;
    @try {
        if (b == 0) {
            [NSException raise:@"B is zero" format:nil];
        } else {
            c = [self problemWithA:a B:b];
        }
    }
    @catch (NSException *exception) {
        const char *temp = UncaughtExceptionHandler(exception);
        NSString *reason = [NSString stringWithCString:temp encoding:NSUTF8StringEncoding];
        [self.webView loadHTMLString:reason baseURL:nil];
    }
    @finally {
        NSLog(@"错误");
    }
    
    // 断言
    NSAssert(b!=0, @"b 是 零");
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
